#include "stdafx.h"
#include "random.h"
#include "qdatetime.h"
#include "assert.h"

Random * Random::m_random = NULL;
int Random::m_distribution[ 5 ][ 5 ] = 
{
//    1   2   3   4   5  
    { 40, 20, 10, 10, 10 },
    { 20, 40, 20, 10, 10 },
    { 20, 20, 40, 20, 20 },
    { 10, 10, 20, 40, 20 },
    { 10, 10, 10, 20, 40 },
};

static int roundToInt( double number )
{
    int num = (int)number;
    return ( ( number + 0.5 ) >= (num + 1 ) ) ? ( num + 1 ) : num;

}

Random::Random()
:   QThread( qApp )
{
    srand ( QDateTime::currentDateTime().toMSecsSinceEpoch() );
}

Random::~Random()
{
}

// pravidelne sa bude reinicializovat random
void Random::run()
{
    while (1)
    {
        srand ( QDateTime::currentDateTime().toMSecsSinceEpoch() );
        sleep( 1000 );
    }
}

const Random & Random::random()
{
    if (m_random == NULL)
        m_random = new Random();

    return * m_random;
}

int Random::random( int minimum, int maximum ) const
{
    return ( minimum + (int)( ( maximum - minimum ) * rand() / ( RAND_MAX + 1.0 ) ) ); 
    //double r = ( (double)qrand() / (double)RAND_MAX ) * ( maximum - minimum );
    //return ( minimum + roundToInt( r ) );
}

int Random::questionValue( int pointPrice ) const
{
    if (pointPrice < 1 || pointPrice > 5)
    {
        assert( 0 );
        return 0;
    }

    int number = random( 1, 100 );
    int value = 0;
    for (int i = 0; i < 5; i ++ )
    {
        value += m_distribution[ i ][ pointPrice - 1 ];
        if (value >= number)
            return ( i + 1 );
    }

    assert( 0 );
    return 0;
}